/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.servicecenter.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.servicecenter.domain.ActivityStatistics;
import com.jeeplus.servicecenter.domain.AssociationApply;
import com.jeeplus.servicecenter.domain.MyUserPost;
import com.jeeplus.servicecenter.domain.MyUserRole;
import com.jeeplus.servicecenter.service.ActivityStatisticsService;
import com.jeeplus.servicecenter.service.ApprovalAssociationApplyService;
import com.jeeplus.servicecenter.service.MyUserPostService;
import com.jeeplus.servicecenter.service.MyUserService;
import com.jeeplus.servicecenter.service.dto.AgreeAssociationApplyDTO;
import com.jeeplus.servicecenter.service.dto.ApprovalAssociationApplyDTO;
import com.jeeplus.servicecenter.service.mapstruct.ApprovalAssociationApplyWrapper;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.domain.Post;
import com.jeeplus.sys.domain.Role;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.PostService;
import com.jeeplus.sys.service.RoleService;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.PostDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 批阅会员申请Controller
 * @author 淋漓
 * @version 2024-05-23
 */

@Api(tags ="批阅会员申请")
@RestController
@RequestMapping(value = "/approval/apply")
public class ApprovalAssociationApplyController {

	@Autowired
	private ApprovalAssociationApplyService associationApplyService;

	@Autowired
	private ApprovalAssociationApplyWrapper associationApplyWrapper;

	@Autowired
	private ActivityStatisticsService activityStatisticsService;

	@Autowired
	private OfficeService officeService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PostService postService;

	@Autowired
	private UserService userService;

	@Autowired
	private MyUserService myUserService;

	@Autowired
	private MyUserPostService myUserPostService;

	/**
	 * 会员申请数据列表数据
	 */
	@ApiLog("查询会员申请数据列表数据")
	@ApiOperation(value = "查询会员申请数据列表数据")
	@PreAuthorize("hasAuthority('approval:apply:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<ApprovalAssociationApplyDTO>> list(ApprovalAssociationApplyDTO associationApplyDTO, Page<AssociationApply> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (associationApplyDTO, ApprovalAssociationApplyDTO.class);
		queryWrapper.eq("result","未处理");
		IPage<ApprovalAssociationApplyDTO> result = associationApplyWrapper.toDTO ( associationApplyService.page (page, queryWrapper) );
		for (ApprovalAssociationApplyDTO item : result.getRecords()) {
			item.setRoleName(roleService.getById(item.getRoleId()).getName());
			item.setOfficeName(officeService.getById(item.getOfficeId()).getName());
		}
		return ResponseEntity.ok (result);
	}


	/**
	 * 根据Id获取会员申请数据数据
	 */
	@ApiLog("根据Id获取会员申请数据数据")
	@ApiOperation(value = "根据Id获取会员申请数据数据")
	@PreAuthorize("hasAnyAuthority('approval:apply:view','approval:apply:add','approval:apply:edit')")
	@GetMapping("queryById")
	public ResponseEntity<ApprovalAssociationApplyDTO> queryById(String id) {
		ApprovalAssociationApplyDTO dto = associationApplyWrapper.toDTO(associationApplyService.getById(id));
		dto.setOfficeName(officeService.getById(dto.getOfficeId()).getName());
		dto.setCompanyName(officeService.getById(dto.getCompanyId()).getName());
		dto.setRoleName(roleService.getById(dto.getRoleId()).getName());
		Post post=postService.getById(dto.getPostId());
		if ( post != null) {
			dto.setPostName(post.getName());
		}
		return ResponseEntity.ok ( dto );
	}

	/**
	 * 同意会员申请数据
	 */
	@ApiLog("同意会员申请数据")
	@ApiOperation(value = "同意会员申请数据")
	@PreAuthorize("hasAnyAuthority('approval:apply:agree')")
	@PostMapping("agree")
	@Transactional
	public  ResponseEntity <String> agree(@Valid @RequestBody AgreeAssociationApplyDTO agree) {
		//判断是否有组织
		List<MyUserRole> myUserRoleList = myUserService.list(new LambdaQueryWrapper<MyUserRole>().eq(MyUserRole::getUserId, agree.getId()));
		if (myUserRoleList!=null) {
			List<RoleDTO> roleDTOList = agree.getRoleDTOList();
			List<PostDTO> postDTOList = agree.getPostDTOList();
			for (MyUserRole myUserRole :myUserRoleList) {
				roleDTOList.add(new RoleDTO(myUserRole.getRoleId()));
			}
			List<MyUserPost> myUserPostList = myUserPostService.list(new LambdaQueryWrapper<MyUserPost>().eq(MyUserPost::getUserId, agree.getId()));
			for (MyUserPost myUserPost : myUserPostList) {
				postDTOList.add(new PostDTO(myUserPost.getPostId()));
			}
			agree.setRoleDTOList(roleDTOList);
			agree.setPostDTOList(postDTOList);
		}
		UserDTO userDTO = BeanUtil.copyProperties(agree, UserDTO.class);
		userService.saveOrUpdate(userDTO);
		associationApplyService.update(new UpdateWrapper<AssociationApply>().set("result", "已同意").set("deal_time", new Date()).eq("id", agree.getId()));
		activityStatisticsService.saveOrUpdate(new ActivityStatistics(agree.getId(),0));
		return ResponseEntity.ok ( "已同意该申请" );
	}

	/**
	 * 拒绝会员申请数据
	 */
	@ApiLog("拒绝会员申请数据")
	@ApiOperation(value = "拒绝会员申请数据")
	@PreAuthorize("hasAnyAuthority('approval:apply:refuse')")
	@GetMapping("refuse")
	public  ResponseEntity <String> refuse(String id) {
		associationApplyService.update(new UpdateWrapper<AssociationApply>().set("result", "已拒绝").set("deal_time", new Date()).eq("id", id));
		return ResponseEntity.ok ( "已拒绝该申请" );
	}

	/**
	 * 保存会员申请数据
	 */
	@ApiLog("保存会员申请数据")
	@ApiOperation(value = "保存会员申请数据")
	@PreAuthorize("hasAnyAuthority('approval:apply:add','approval:apply:edit')")
	@PostMapping("save")
	public  ResponseEntity <String> save(@Valid @RequestBody ApprovalAssociationApplyDTO associationApplyDTO) {
		//新增或编辑表单保存
		associationApplyService.saveOrUpdate (associationApplyWrapper.toEntity (associationApplyDTO));
        return ResponseEntity.ok ( "保存会员申请数据成功" );
	}


	/**
	 * 删除会员申请数据
	 */
	@ApiLog("删除会员申请数据")
	@ApiOperation(value = "删除会员申请数据")
	@PreAuthorize("hasAuthority('approval:apply:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        associationApplyService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除会员申请数据成功" );
	}
	
    /**
     * 导出会员申请数据数据
     *
     * @param associationApplyDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出会员申请数据数据")
    @PreAuthorize("hasAnyAuthority('approval:apply:export')")
    @GetMapping("export")
    public void exportFile(ApprovalAssociationApplyDTO associationApplyDTO, Page <AssociationApply> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (associationApplyDTO, ApprovalAssociationApplyDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据
            
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List < AssociationApply> result = associationApplyService.page ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( associationApplyService, associationApplyWrapper ).exportExcel ( result,  options.getSheetName ( ), ApprovalAssociationApplyDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入会员申请数据数据
     *
     * @return
     */
    /*@PreAuthorize("hasAnyAuthority('approval:apply:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( associationApplyService, associationApplyWrapper ).importExcel ( file, ApprovalAssociationApplyDTO.class );
        return ResponseEntity.ok ( result );
    }*/

    /**
     * 下载导入会员申请数据数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('approval:apply:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "会员申请数据数据导入模板.xlsx";
        List<ApprovalAssociationApplyDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( associationApplyService, associationApplyWrapper ).exportExcel ( list,  "会员申请数据数据", ApprovalAssociationApplyDTO.class, fileName, null, response );
    }


}
